package ua.kiev.tosik.price.modules.clients.gui;

import org.jdesktop.swingx.JXPanel;
import ua.kiev.tosik.price.gui.StatusBar;
import ua.kiev.tosik.price.modules.clients.CompaniesModule;
import ua.kiev.tosik.price.modules.clients.database.DataLoadWorker;
import ua.kiev.tosik.price.modules.clients.gui.prices.PricesDialog;

import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

public class MainPanel implements PropertyChangeListener {

	private static MainPanel ourInstance;
	private JXPanel panel;
	private ClientsTable table;
	private CompaniesModule module;
	private MainToolBar toolBar;

	public static MainPanel getInstance() {
		if (ourInstance == null) {
			ourInstance = new MainPanel();
		}
		return ourInstance;
	}

	public JXPanel getPanel() {
		return panel;
	}

	public ClientsTable getTable() {
		return table;
	}

	public CompaniesModule getModule() {
		return module;
	}

	public void setModule(CompaniesModule module) {
		this.module = module;
	}

	private MainPanel() {
		panel = new JXPanel();
		table = new ClientsTable();
		panel.setLayout( new BorderLayout() );

		toolBar = new MainToolBar();
		panel.add(toolBar.getToolBar(), BorderLayout.NORTH);
		panel.add(table.getTable(), BorderLayout.CENTER);

		table.getModel().addTableModelListener(toolBar);

		loadData();

	}

	public MainToolBar getToolBar() {
		return toolBar;
	}

	public void loadData() {
		DataLoadWorker loadWorker = new DataLoadWorker();
		loadWorker.addPropertyChangeListener(StatusBar.getInstance());
		loadWorker.addPropertyChangeListener(this);
		loadWorker.execute();
	}

	public void destroy() {
		PricesDialog.destroy();
		panel = null;
		table = null;
		toolBar = null;
		ourInstance = null;
	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if ( evt.getPropertyName().endsWith("_START") ) {
			toolBar.setEnable(false);
		}
		if ( evt.getPropertyName().endsWith("_DONE") || evt.getPropertyName().endsWith("_OK") ) {
			toolBar.setEnable(true);
		}
		if ( evt.getPropertyName().equals("FILE_DELETE_ALL_OK") ) {
			loadData();
		}
	}
}
